/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.document.scheme;

import cn.ac.nercis.pes.common.constant.common.BaseConstants;
import cn.ac.nercis.pes.common.constant.common.ReportConstants;
import cn.ac.nercis.pes.common.constant.evaluation.ReportType;
import cn.ac.nercis.pes.common.constant.knowledge.AssetClassification;
import cn.ac.nercis.pes.common.constant.knowledge.EvaluationMethod;
import cn.ac.nercis.pes.common.constant.knowledge.LayerTarget;
import cn.ac.nercis.pes.common.constant.knowledge.TargetDeepness;
import cn.ac.nercis.pes.common.constant.project.SpecialType;
import cn.ac.nercis.pes.common.utils.ConvertUtils;
import cn.ac.nercis.pes.common.utils.DataUtils;
import cn.ac.nercis.pes.model.bo.doc.common.evaluation.NetworkTopologyBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.EvaluationContentBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.EvaluationPlanBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.SystemSituationBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.content.LayerContentBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.plan.AnalysisPlanDetailBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.plan.CompilationPlanDetailBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.plan.EvaluationPlanDetailBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.evaluation.plan.PreparationPlanDetailBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.system.SystemBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.table.EvalContentSchemeBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.table.EvalRequireSchemeBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.table.EvaluationAssetSchemeBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.unit.EvaluationUnitBO;
import cn.ac.nercis.pes.model.bo.doc.scheme.unit.TestedUnitBO;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.evaluation.content.NetworkTopologyDTO;
import cn.ac.nercis.pes.model.dto.evaluation.content.plan.AnalysisPlanDetailDTO;
import cn.ac.nercis.pes.model.dto.evaluation.content.plan.CompilationPlanDetailDTO;
import cn.ac.nercis.pes.model.dto.evaluation.content.plan.EvaluationPlanDetailDTO;
import cn.ac.nercis.pes.model.dto.evaluation.content.plan.PreparationPlanDetailDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.AssetEvaluationMethodRepository;
import cn.ac.nercis.pes.repository.dal.evaluation.AssetRepository;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationProcessRepository;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationRequireRepository;
import cn.ac.nercis.pes.repository.dal.manage.EvaluationUnitRepository;
import cn.ac.nercis.pes.repository.dal.manage.TestedUnitRepository;
import cn.ac.nercis.pes.repository.dal.project.SystemSpecialTargetRepository;
import cn.ac.nercis.pes.repository.dal.project.SystemTargetRepository;
import cn.ac.nercis.pes.repository.dal.report.EvaluationReportRepository;
import cn.ac.nercis.pes.repository.mapper.evaluation.EvaluationProcessMapper;
import cn.ac.nercis.pes.repository.mapper.manage.PasswordConditionMapper;
import cn.ac.nercis.pes.repository.model.evaluation.AssetDO;
import cn.ac.nercis.pes.repository.model.evaluation.AssetEvaluationMethodDO;
import cn.ac.nercis.pes.repository.model.manage.EvaluationUnitDO;
import cn.ac.nercis.pes.repository.model.manage.TestedUnitDO;
import cn.ac.nercis.pes.repository.model.project.*;
import cn.ac.nercis.pes.repository.model.report.EvaluationReportDO;
import cn.ac.nercis.pes.service.document.common.DocDataService;
import cn.ac.nercis.pes.service.document.report.ReportAssetDataService;
import cn.ac.nercis.pes.service.document.common.DocTargetDataService;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import cn.ac.nercis.pes.service.evaluation.EvaluationProcessService;
import cn.ac.nercis.pes.service.evaluation.EvaluationToolsService;
import cn.ac.nercis.pes.service.evaluation.SecurityThreatService;
import cn.ac.nercis.pes.service.utils.AssetUtils;
import cn.ac.nercis.pes.service.utils.FileManage;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 密评方案数据服务类
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public record SchemeDataService(EvaluationReportRepository evaluationReportRepository,
                                TestedUnitRepository testedUnitRepository,
                                EvaluationUnitRepository evaluationUnitRepository,
                                EvaluationProcessRepository evaluationProcessRepository,
                                EvaluationContentService evaluationContentService,
                                EvaluationProcessService evaluationProcessService,
                                SecurityThreatService securityThreatService,
                                ReportAssetDataService reportAssetDataService,
                                SystemTargetRepository systemTargetRepository,
                                SystemSpecialTargetRepository systemSpecialTargetRepository,
                                AssetEvaluationMethodRepository assetEvaluationMethodRepository,
                                AssetRepository assetRepository,
                                EvaluationRequireRepository evaluationRequireRepository,
                                DocTargetDataService docTargetDataService,
                                EvaluationToolsService evaluationToolsService,
                                DocDataService docDataService) {



    private final static String NEWLINE_CHAR = "\\n";

    public String getSchemeCode(@NonNull SystemDO systemDO) {
        try {
            return DataUtils.findFirst(evaluationReportRepository.findBySystemIdAndReportType(systemDO.getId(), ReportType.SCHEME))
                    .map(EvaluationReportDO::getCode)
                    .orElse(defaultSchemeCode(systemDO));
        } catch (RuntimeException rEx) {
            log.error("{}/getSchemeCode 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public String getTestedUnitSystemName(@NonNull SystemDO systemDO) {
        try {
            return systemDO.getProject().getTestedUnit().concat(systemDO.getName());
        } catch (RuntimeException rEx) {
            log.error("{}/getTestedUnitSystemName 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public TestedUnitBO getTestedUnit(@NonNull SystemDO systemDO) throws Exception {
        try {
            TestedUnitDO testedUnitDO = testedUnitRepository.findById(systemDO.getProject().getTestedUnitId()).orElse(null);
            if (Objects.isNull(testedUnitDO)) {
                throw new Exception(ResultCode.TESTED_UNIT_NOT_EXIST.getMsg());
            }
            return TestedUnitBO.builder()
                    .name(testedUnitDO.getName())
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getTestedUnit 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public EvaluationUnitBO getEvaluationUnit() throws Exception {
        try {
            EvaluationUnitDO evaluationUnitDO = this.evaluationUnitRepository.findAll().stream()
                    .findFirst()
                    .orElse(null);
            if (Objects.isNull(evaluationUnitDO)) {
                throw new Exception(ResultCode.EVALUATION_UNIT_NOT_EXIST.getMsg());
            }
            return EvaluationUnitBO.builder()
                    .name(evaluationUnitDO.getName())
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getEvaluationUnit 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }


    public String getEntrustedUnitName(@NonNull SystemDO systemDO) {
        try {
            return Optional.of(systemDO.getProject())
                    .map(ProjectDO::getRequesterUnit)
                    .orElse("");
        } catch (RuntimeException rEx) {
            log.error("{}/getEntrustedUnitName 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public SystemBO getSystem(@NonNull SystemDO systemDO, @NonNull SystemEvaluationDO evaluationDO) {
        try {
            return SystemBO.builder()
                    .name(systemDO.getName())
                    .level(systemDO.getSecurityLevel().getName())
                    .sLevel(String.valueOf(systemDO.getSLevel()))
                    .aLevel(String.valueOf(systemDO.getALevel()))
                    .gLevel(String.valueOf(systemDO.getGLevel()))
                    .filingNumber(systemDO.getFilingNumber())
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getSystem 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public SystemSituationBO getSystemSituation(@NonNull SystemDO systemDO) {
        try {
            var businessContent = evaluationContentService.findBusinessCondition(systemDO.getId());
            NetworkTopologyDTO topologyDTO = evaluationContentService.findNetworkTopology(systemDO.getId());
            return SystemSituationBO.builder()
                    .businessFileDir(FileManage.getBusinessContentDir(systemDO.getId()))
                    .businessCondition(businessContent.getContent())
                    .networkTopology(NetworkTopologyBO.builder()
                            .zoneSummary(topologyDTO.getZoneSummary())
                            .topologyDir(FileManage.getNetworkTopologyDir(systemDO.getId()))
                            .topologyPicture(topologyDTO.getTopologyPicture())
                            .zoneIllustrate(topologyDTO.getZoneIllustrate())
                            .build())
                    .passwordCondition(PasswordConditionMapper.INSTANCE.toPasswordConditionBO(
                            evaluationContentService.findPasswordCondition(systemDO.getId())))
                    .systemAsset(reportAssetDataService.getSystemAssetData(systemDO))
                    .pwdServiceTable(docDataService.getPwdServiceTable(systemDO.getId()))
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getSystemSituation 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public EvaluationPlanBO getEvaluationPlan(@NonNull SystemDO systemDO) {
        try {
            PreparationPlanDetailDTO preparationPlan = evaluationProcessService.getPreparationPlanDetail(systemDO.getId());
            CompilationPlanDetailDTO compilationPlan = evaluationProcessService.getCompilationPlanDetail(systemDO.getId());
            EvaluationPlanDetailDTO evaluationPlan = evaluationProcessService.getEvaluationPlanDetail(systemDO.getId());
            AnalysisPlanDetailDTO analysisPlan = evaluationProcessService.getAnalysisPlanDetail(systemDO.getId());
            return EvaluationPlanBO.builder()
                    .preparation(Objects.nonNull(preparationPlan) ? EvaluationProcessMapper.INSTANCE.toPreparationPlanDetailBO(preparationPlan) : getPreparationPlanByEmpty())
                    .compilation(Objects.nonNull(compilationPlan) ? EvaluationProcessMapper.INSTANCE.toCompilationPlanDetailBO(compilationPlan) : getCompilationPlanByEmpty())
                    .evaluation(Objects.nonNull(evaluationPlan) ? EvaluationProcessMapper.INSTANCE.toEvaluationPlanDetailBO(evaluationPlan) : getEvaluationPlanByEmpty())
                    .analysis(Objects.nonNull(analysisPlan) ? EvaluationProcessMapper.INSTANCE.toAnalysisPlanDetailBO(analysisPlan) : getAnalysisPlanByEmpty())
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getEvaluationPlan 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public EvaluationContentBO getEvaluationContent(@NonNull SystemDO systemDO) {
        try {
            List<SystemTargetDO> systemTargets = systemTargetRepository.findAllBySystemId(systemDO.getId());
            List<SystemSpecialTargetDO> specialTargets = systemSpecialTargetRepository.findAllBySystemId(systemDO.getId());
            List<AssetEvaluationMethodDO> assetMethods = assetEvaluationMethodRepository.findAllBySystemId(systemDO.getId());
            List<AssetDO> assets = assetRepository.findAllBySystemId(systemDO.getId());
            return EvaluationContentBO.builder()
                    .phyEnv(getLayerEvalContentData(LayerTarget.PHY_ENV, systemTargets, specialTargets, assetMethods, assets))
                    .netCommunication(getLayerEvalContentData(LayerTarget.NET_COMMUNICATION, systemTargets, specialTargets, assetMethods, assets))
                    .deviceCompute(getLayerEvalContentData(LayerTarget.DEVICE_COMPUTE, systemTargets, specialTargets, assetMethods, assets))
                    .appData(getLayerEvalContentData(LayerTarget.APP_DATA, systemTargets, specialTargets, assetMethods, assets))
                    .manageSystem(getLayerEvalContentData(LayerTarget.MANAGE_SYSTEM, systemTargets, specialTargets, assetMethods, assets))
                    .personnelManage(getLayerEvalContentData(LayerTarget.PERSONNEL_MANAGE, systemTargets, specialTargets, assetMethods, assets))
                    .buildRunning(getLayerEvalContentData(LayerTarget.BUILD_RUNNING, systemTargets, specialTargets, assetMethods, assets))
                    .emergencyHandling(getLayerEvalContentData(LayerTarget.EMERGENCY_HANDLING, systemTargets, specialTargets, assetMethods, assets))
                    .build();
        } catch (RuntimeException rEx) {
            log.error("{}/getEvaluationContent 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    public List<EvaluationAssetSchemeBO> getEvaluationAsset(@NonNull SystemDO systemDO) {
        try {
            List<AssetEvaluationMethodDO> evaluationMethods = assetEvaluationMethodRepository.findAllBySystemId(systemDO.getId());
            List<AssetDO> assets = assetRepository.findAllBySystemId(systemDO.getId()).stream()
                    .filter(a -> Objects.nonNull(a.getIsUse()) && a.getIsUse())
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(evaluationMethods) || CollectionUtils.isEmpty(assets)) {
                return getEvaluationAssetByEmpty();
            }
            Set<String> layerTargetIds = evaluationMethods.stream()
                    .map(AssetEvaluationMethodDO::getLayerTargetId)
                    .collect(Collectors.toSet());
            List<EvaluationAssetSchemeBO> tableData = systemTargetRepository.findAllBySystemIdAndKmTargetIdIn(systemDO.getId(), layerTargetIds)
                    .stream()
                    .sorted(Comparator.comparingInt(SystemTargetDO::getKmSort))
                    .flatMap(kt -> getEvaluationAssetData(kt, evaluationMethods, assets).stream())
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(tableData)) {
                return getEvaluationAssetByEmpty();
            }
            return tableData;
        } catch (RuntimeException rEx) {
            log.error("{}/getEvaluationAsset 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }

    List<EvaluationAssetSchemeBO> getEvaluationAssetData(SystemTargetDO layerTarget, List<AssetEvaluationMethodDO> evaluationMethods,
                                                             List<AssetDO> assets) {
        Set<String> assetIds = evaluationMethods.stream()
                .filter(em -> StringUtils.equals(em.getLayerTargetId(), layerTarget.getKmTargetId())
                        && (!StringUtils.equals(em.getClassId(), AssetClassification.KEY_BUSINESS.getId()) || (!StringUtils.equals(em.getClassId(), AssetClassification.KEY_DATA.getId()))))
                .map(AssetEvaluationMethodDO::getAssetId)
                .collect(Collectors.toSet());
        return assets.stream()
                .filter(a -> assetIds.stream().anyMatch(id -> StringUtils.equals(a.getId(), id)))
                .map(asset -> getEvaluationAssetData(layerTarget, asset))
                .collect(Collectors.toList());
    }

    private EvaluationAssetSchemeBO getEvaluationAssetData(SystemTargetDO layerTarget, AssetDO assetDO) {
        return EvaluationAssetSchemeBO.builder()
                .layer(layerTarget.getKmName())
                .asset(AssetUtils.getAssetName(assetDO))
                .desc(assetDO.getDesc())
                .build();
    }
    private List<EvaluationAssetSchemeBO> getEvaluationAssetByEmpty() {
        return List.of(EvaluationAssetSchemeBO.builder()
                .layer("")
                .asset("")
                .desc("")
                .build());
    }

    private LayerContentBO getLayerEvalContentData(LayerTarget layerTarget, List<SystemTargetDO> systemTargets,
                                                   List<SystemSpecialTargetDO> specialTargets,
                                                   List<AssetEvaluationMethodDO> assetMethods,
                                                   List<AssetDO> assets) {
        SystemTargetDO lt = systemTargets.stream()
                .filter(st -> StringUtils.equals(st.getKmName(), layerTarget.getName())
                        && st.getKmDeepness() == TargetDeepness.LAYER.getDeepness())
                .findFirst().orElse(null);
        return LayerContentBO.builder()
                .content(getEvalContentTableData(lt, systemTargets, specialTargets, assetMethods, assets))
                .require(getRequireTableData(lt))
                .build();
    }


    public List<EvalContentSchemeBO> getEvalContentTableData(SystemTargetDO layerTarget, List<SystemTargetDO> systemTargets,
                                                             List<SystemSpecialTargetDO> specialTargets,
                                                             List<AssetEvaluationMethodDO> assetMethods,
                                                             List<AssetDO> assets) {
        try {
            if (Objects.isNull(layerTarget)) {
                return getEvalContentTableDataByEmpty();
            }
            AtomicInteger number = new AtomicInteger(1);
            List<EvalContentSchemeBO> tableData = systemTargets.stream()
                    .filter(st -> StringUtils.equals(st.getKmParentId(), layerTarget.getKmTargetId()))
                    .sorted(Comparator.comparingInt(SystemTargetDO::getKmSort))
                    .flatMap(ut -> getEvalContentTableData(number, ut, systemTargets, assetMethods, assets).stream())
                    .collect(Collectors.toList());
            List<EvalContentSchemeBO> tableSpecialData = specialTargets.stream()
                    .filter(st -> StringUtils.equals(st.getLayerTargetId(), layerTarget.getKmTargetId())
                            && st.getSpecialType() != SpecialType.UPGRADE)
                    .sorted(Comparator.comparingInt(SystemSpecialTargetDO::getSort))
                    .flatMap(ut -> getEvalContentTableData(number, ut, assetMethods, assets).stream())
                    .toList();
            if (CollectionUtils.isEmpty(tableData) && CollectionUtils.isEmpty(tableSpecialData)) {
                return getEvalContentTableDataByEmpty();
            }
            return Stream.concat(tableData.stream(), tableSpecialData.stream()).toList();
        } catch (RuntimeException rEx) {
            log.error("{}/getEvalContentTableData 获取数据出错：{}", this.getClass().getName(), rEx.getMessage());
            throw rEx;
        }
    }
    private List<EvalContentSchemeBO> getEvalContentTableData(AtomicInteger number, SystemTargetDO unitTarget,
                                                              List<SystemTargetDO> systemTargets,
                                                              List<AssetEvaluationMethodDO> assetMethods,
                                                              List<AssetDO> assets) {
        String evalTarget = systemTargets.stream()
                .filter(st -> StringUtils.equals(st.getKmParentId(), unitTarget.getKmTargetId()))
                .map(SystemTargetDO::getKmName)
                .findFirst().orElse("");

        List<EvalContentSchemeBO> rowData = assetMethods.stream()
                .filter(aem -> StringUtils.equals(aem.getUnitTargetId(), unitTarget.getKmTargetId()))
                .map(aem -> getEvalContentTableData(number, unitTarget, evalTarget, aem, assets))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(rowData)) {
            number.getAndIncrement();
        }
        return rowData;
    }

    private EvalContentSchemeBO getEvalContentTableData(AtomicInteger number, SystemTargetDO unitTarget,
                                                        String evalTarget,
                                                        AssetEvaluationMethodDO assetMethod,
                                                        List<AssetDO> assets) {
        String methods = Stream.of(StringUtils.split(assetMethod.getMethod(), BaseConstants.MULTI_SPLIT_CHAR))
                .map(ConvertUtils::toInteger)
                .map(EvaluationMethod::fromMethod)
                .filter(em->em!=EvaluationMethod.DEFAULT)
                .map(EvaluationMethod::getName)
                .collect(Collectors.joining(NEWLINE_CHAR));
        String assetName = assets.stream()
                .filter(a -> StringUtils.equals(a.getId(), assetMethod.getAssetId()))
                .map(AssetUtils::getAssetName)
                .findFirst().orElse("");
        return EvalContentSchemeBO.builder()
                .number(String.valueOf(number.get()))
                .unitTarget(unitTarget.getKmName())
                .evalTarget(evalTarget)
                .assetName(assetName)
                .content(assetMethod.getDesc())
                .method(methods)
                .build();
    }

    List<EvalContentSchemeBO> getEvalContentTableData(AtomicInteger number, SystemSpecialTargetDO unitTarget,
                                                              List<AssetEvaluationMethodDO> assetMethods,
                                                              List<AssetDO> assets) {
        List<EvalContentSchemeBO> rowData = assetMethods.stream()
                .filter(aem -> StringUtils.equals(aem.getUnitTargetId(), unitTarget.getId()))
                .map(aem -> getEvalContentTableData(number, unitTarget, aem, assets))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(rowData)) {
            number.getAndIncrement();
        }
        return rowData;
    }

    private EvalContentSchemeBO getEvalContentTableData(AtomicInteger number, SystemSpecialTargetDO unitTarget,
                                                        AssetEvaluationMethodDO assetMethod,
                                                        List<AssetDO> assets) {
        String methods = Stream.of(StringUtils.split(assetMethod.getMethod(), BaseConstants.MULTI_SPLIT_CHAR))
                .map(ConvertUtils::toInteger)
                .map(EvaluationMethod::fromMethod)
                .filter(em->em!=EvaluationMethod.DEFAULT)
                .map(EvaluationMethod::getName)
                .collect(Collectors.joining(NEWLINE_CHAR));
        String assetName = assets.stream()
                .filter(a -> StringUtils.equals(a.getId(), assetMethod.getAssetId()))
                .map(AssetUtils::getAssetName)
                .findFirst().orElse("");
        return EvalContentSchemeBO.builder()
                .number(String.valueOf(number.get()))
                .unitTarget(unitTarget.getName())
                .evalTarget(unitTarget.getTargetDesc())
                .assetName(assetName)
                .content(assetMethod.getDesc())
                .method(methods)
                .build();
    }
    private List<EvalRequireSchemeBO> getRequireTableData(SystemTargetDO layerTarget) {
        if (Objects.isNull(layerTarget)) {
            return getRequireTableDataByEmpty();
        }
        var evaluationRequires = evaluationRequireRepository.findAllBySystemIdAndLayerTargetId(layerTarget.getSystemId(), layerTarget.getKmTargetId());
        if (CollectionUtils.isEmpty(evaluationRequires)) {
            return getRequireTableDataByEmpty();
        }
        AtomicInteger number = new AtomicInteger(1);
        return evaluationRequires.stream().map(item -> EvalRequireSchemeBO.builder()
                        .number(String.valueOf(number.getAndIncrement()))
                        .project(item.getProject())
                        .require(item.getRequire())
                        .build())
                .toList();
    }

    private List<EvalRequireSchemeBO> getRequireTableDataByEmpty(){
        return List.of(EvalRequireSchemeBO.builder()
                .number("1")
                .project("")
                .require("")
                .build());

    }

    private List<EvalContentSchemeBO> getEvalContentTableDataByEmpty(){
        return List.of(EvalContentSchemeBO.builder()
                .number("1")
                .unitTarget("")
                .evalTarget("")
                .assetName("")
                .content("")
                .method("")
                .build());
    }
    private PreparationPlanDetailBO getPreparationPlanByEmpty() {
        return PreparationPlanDetailBO.builder()
                .projectStart("组建等级测评项目组，从资料、人员、计划安排等方面为整个等级测评项目的实施做好准备。")
                .collectAnalyze("查阅已有资料或使用调查表单的方式，了解整个系统的构成和保护情况，为编写测评方案和开展现场测评工作奠定基础。")
                .toolPrepare("确认测评工具；打印的各类文档：现场测评授权书、测评结果记录表格（含测评人员入场和离场确认）、文档交接单。")
                .build();
    }

    private CompilationPlanDetailBO getCompilationPlanByEmpty() {
        return CompilationPlanDetailBO.builder()
                .assetDefine("根据已经了解到的资金管理系统信息，分析整个被测系统和各测评业务系统确定出本次测评的测评对象。")
                .targetDefine("根据已经了解到的被测系统定级结果，确定出本次测评的测评指标。")
                .checkPointDefine("测评过程中，需要对一些关键安全点进行现场检查确认，以防止密码产品、密码服务虽然被正确配置，但是未接入被测信息系统之类的情况发生。")
                .contentDefine("确定现场测评的具体实施内容，包括单元测评和系统测评。")
                .schemeMake("完成测评方案编制，方案包括：项目概述、测评对象、测评指标、测评工具的接入点、单元测评实施、系统测评实施以及配套的测评实施手册。")
                .build();
    }

    private EvaluationPlanDetailBO getEvaluationPlanByEmpty() {
        return EvaluationPlanDetailBO.builder()
                .implementPrepare("实施现场测评的启动过程，确认更新后的测评计划和测评程序，确认授权委托书。")
                .sceneRecord("通过访谈、文档审查、配置检查、工具测试和实地察看，测评方对技术安全和管理安全测评的测评结果记录；同时现场监督员对测评方的工作做好监督。")
                .resultDefine("委托方对现场测评结果记录进行确认，测评方归还相关资料。")
                .build();
    }

    private AnalysisPlanDetailBO getAnalysisPlanByEmpty() {
        return AnalysisPlanDetailBO.builder()
                .unitEval("汇总统计各测评指标的各个测评对象的测评结果，给出单元测评结果")
                .overallEval("分析被测信息系统整体安全状况及对各测评对象测评结果的修正情况")
                .quantifyEval("综合单元测评和整体测评结果，计算得分，并对被测信息系统的密码应用情况安全性进行总体评价")
                .riskAnalyze("分析被测信息系统存在的安全问题风险情况")
                .evalConclusion("对测评结果进行分析，形成评估结论")
                .secretReport("完成密评报告编制，报告包括概述、被测信息系统描述、测评对象说明、测评指标说明、测评内容和方法说明、单元测评、整体测评、量化评估、风险分析、评估结论和改进建议等")
                .build();
    }




    private String defaultSchemeCode(SystemDO systemDO) {
        //项目编号+系统顺序号
        String reportCode = String.format("%s-%02d", systemDO.getProject().getNumber(), systemDO.getSort());
        return ReportConstants.PES_SCHEME_CODE_PREFIX.concat(reportCode);
    }

}
